<?php

namespace app\api\logic;

use app\data\util\HttpUtil;
use think\facade\Db;
use app\api\logic\FeiShuTalkLogic;
class ShopyLogic extends BasicLogic
{


    /**
     * @desc    获取报告列表信息
     * @date    2024/09/05
     * @author  luckyXiong
     */
    public function get_report_list($order=[]){
        $shop_id         = $order['shop_id']??'';
        $shop_info       = Db::name('shops')->where('id',$shop_id)->find();
        $fulfill_url     = $shop_info['myshopify_domain'] . Config('Logisticskey.shopify.get_report_list');
        return HttpUtil::getUrl($fulfill_url, $shop_info);
    }



    public function get_report_info($order=[]){
        $shop_id           = $order['shop_id']??'';
        $report_id         = $order['report_id']??'';
        $shop_info       = Db::name('shops')->where('id',$shop_id)->find();
        $fulfill_url     = $shop_info['myshopify_domain'] . Config('Logisticskey.shopify.get_report_info').$report_id.'.json';
        $report_info     = HttpUtil::getUrl($fulfill_url, $shop_info);
        return $report_info;
    }





    /**
     * @desc    获取报告详情
     * @date    2024/09/05
     * @author  luckyXiong
     */
    public function create_report_info($order=[])
    {
        $shop_id     = $order['shop_id'] ?? '';
        $shop_info   = Db::name('shops')->where('id', $shop_id)->find();
        $fulfill_url = $shop_info['myshopify_domain'] . Config('Logisticskey.shopify.get_report_list');
        $data_fulfillments = [
            "report"              => [
                'notify_customer' => false,
                "name"            => "A new app report3",
                'shopify_ql'      => "SHOW orders, average_units_ordered, average_order_value, returned_item_quantity_abs OVER day FROM sales SINCE -30d UNTIL today ORDER BY hour",
            ],
        ];
        $token        = $shop_info['app_secret'];
        $return       = HttpUtil::postUrlShopify($fulfill_url, $data_fulfillments, $token);
        return json_decode($return, true);
     }




    /**
     * @desc    获取报告详情
     * @date    2024/09/05
     * @author  luckyXiong
     */
    public function get_spu_fee(){
        $t1         = microtime(true);
        $order_ids  = [];
        $shop_id     = 17;
        $where       = [];
        $date['0']   = '2024-09-01 00:00:00';
        $date['1']   = '2024-09-01 23:59:59';
        $where[]     = ['createtime', '>=', strtotime($date['0'])];
        $where[]     = ['createtime', '<=', strtotime($date['1'])];
        $where[]     = ['shop_id', '=', $shop_id];
        $where[]     = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $list        = Db::name('order_info')->field('order_id,sku,spu,quantity')->whereIN('order_id',$order_ids)->select()->toArray();
        $order_id    = array_column($list,'order_id');
        $info        = Db::name('order_info')->field('order_id,sku,spu,quantity')->where('order_id','6142025269309')->select()->toArray();
        $arr         = [];

        foreach($info as $v){
            if(!$v['sku']) continue;
            $temp = [
                'order_id'        =>$v['order_id'],
                'sku'             =>get_shopify_spu($v['sku'],$v['quantity']),
                'num'             =>$v['quantity'],
                'spu'             =>$v['spu'],
            ];
            $arr[]  = $temp;
        }

        foreach($arr as $k=>$v){
            $sum = 1;
            if(strpos($v['sku'],',')){
               $arr_sku = explode(',',$v['sku']);
               $current = current($arr_sku);
                if(preg_match('/.*-(\d+)$/', $current, $matches)){
                    $sum = $matches[1];
                }
                $sum = $sum*count($arr_sku);
            }else{
                if(preg_match('/.*-(\d+)$/', $v['sku'], $matches)){
                    $sum = $matches[1];
                }
            }
                $arr[$k]['num'] = $sum;
        }



        foreach($list as $k=>$v){
            echo PHP_EOL . '执行第' .($k+1).'条'. PHP_EOL;
            $sku = explode(',',$v['sku']);
            self::insert_info($sku,$v['order_id']);

        }
        echo PHP_EOL . '结束' . PHP_EOL;
        echo  PHP_EOL ."get_spu_fee-定时执行总耗时:".round( microtime(true) - $t1, 3). PHP_EOL;
    }




    /**
     * @desc  get_unique_sku
     * @author xx
     * @date 2024-07-13
     */
    public function test_send_message($params=[]){
        $date  = $params['date'] ?? "";
        $where    = [];
        $where[] = ['c.createtime', '>=', strtotime($date['0'])];
        $where[] = ['c.createtime', '<=', strtotime($date['1']) + 3600*24-1];

        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[] = ['a.spu', 'LIKE', "%swim%"];
        $list = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as skuquantity,
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->order('skuquantity desc')
            ->select()
            ->toArray();

        $arr = [];

        $date1 = substr($date['0'],0,7);
        foreach($list as $k=>$v){
            $temp = [
                'spu'         =>$v['spu'],
                'date'        =>$date1,
                'new_quantity'=>$v['skuquantity'],
            ];
            $arr[] = $temp;
        }


        $info = Db::name('inventory_log')->insertAll(
            $arr
        );





    }


    /**
     * @desc   获取sku信息
     * @author luckyXiong
     * @date   2025-03-03
     */
    public function get_sku_info($params=[]){
           $sku = $params['sku']??'';
           $info= get_product_sku($sku,1);
           return $info;
    }


    /**
     * @desc  获取提成比例
     * @author xx
     * @date 2024-09-20
     */
    public function get_channel_rate($params=[]){
        $total_price  = $params['total_price']??'';
        $channel_type = $params['channel_type']??'';
        if(!$total_price){
            return $this->jsonMessage(201,false,'提成金额不能为空',null);
        }
        if(!$channel_type){
            return $this->jsonMessage(201,false,'广告渠道不能为空',null);
        }
        $where   = [];
        $where[] = ['channel_type','=',$channel_type];
        $where[] = ['max_price','>=',$total_price];
        $where[] = ['min_price','<',$total_price];
        $info    = Db::name('order_channel_rate')->where($where)->field('id,rate')->order('id asc')->find();
        $rate    = $info['rate']??0;
        return $rate;
        // return  $this->jsonMessage(201,false,'广告渠道不能为空',$rate);
    }





    /**
     * @desc  获取是否组长判断
     * @author xx
     * @date 2024-09-20
     */
    public function get_team_info($params=[]){
           $user_name    = $params['user_name']??'';
           $date         = $params['date']??'';
           $user_name    = trim($user_name);
           $date         = trim($date);
           if(!$user_name){
               return  $this->jsonMessage(201,false,'名字不能为空',null);
           }
           if(!$date){
               return  $this->jsonMessage(201,false,'日期不能为空',null);
           }
           $where   = [];
           $where[] = ['user_name','=',$user_name];
           $where[] = ['date','=',$date];

           $info    = Db::name('order_operate_name')->where($where)->field('id,user_name')->find();
           $id      = $info['id']??'';
           $is_team = $id ? 1 : '';
           return  $this->jsonMessage(200,true,'获取成功',$is_team);
    }



    /**
     * @desc  获取是否组长判断
     * @author xx
     * @date 2024-09-20
     */
    public function get_advertistment_info($params){
           $updatetime_automatic_last = $params['updatetime_automatic_last']??'';
           $advertiser_id        = $params['advertiser_id']??'';
           $platform_id          = $params['platform_id']??'';
           $id                   = $params['id']??'';
           $data  = [
                 'updatetime_automatic_last' => $updatetime_automatic_last,
                 'advertiser_id'             => $advertiser_id,
                 'platform_id'               => $platform_id,
                 'id'                        => $id,
           ];
           $info  = (new ApiAdvLogic())->integrated_get_info($data);
           return  $this->jsonMessage(200,true,'获取成功',$info);
    }







}